package com.atguigu.gmall.gateway.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @author: atguigu
 * @create: 2023-08-29 11:44
 */
@Configuration
public class CorsConfig {


    /**
     * 注册CORS过滤器规则，将来拦截经过网关所有请求，统一解决跨域
     *
     * @return
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        //1.配置cors策略
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //1.1. 设置允许哪些域名可以跨域访问
        corsConfiguration.addAllowedOrigin("*");
        //1.2. 设置允许哪些请求头可以跨域访问
        corsConfiguration.addAllowedHeader("*");
        //1.3. 设置允许哪些请求方式可以跨域访问
        corsConfiguration.addAllowedMethod("*");
        //1.4. 设置允许携带cookie
        corsConfiguration.setAllowCredentials(true);
        //1.5. 设置预检请求有效期
        corsConfiguration.setMaxAge(3600L);

        //2.注册策略
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        //注册CORS配置策略
        corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(corsConfigurationSource);
    }
}
